package com.novel.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpUtils {
	
	
	public static void main(String[] args) throws Exception {
		HttpUtils utils = new HttpUtils();
		String s = utils.getContentFromIn("http://www.zanghaihua.org/2425.html", "utf-8");
		System.out.println(s);
	}

	public String getContentFromIn(String urlPath, String charset)
			throws Exception {
		URL url = new URL(urlPath);
		HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
		urlConn.setRequestProperty("User-Agent",
				"Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)");
		urlConn.setRequestProperty(
				"Accept",
				"image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-powerpoint, application/vnd.ms-excel, application/msword, */*");
		urlConn.setRequestProperty("Accept-Language", "zh-cn");
		urlConn.setRequestProperty("UA-CPU", "x86");
		urlConn.setRequestProperty("Accept-Encoding", "gzip");
		urlConn.setRequestProperty("Content-type", "text/html");
		urlConn.setRequestProperty("Connection", "close");

		urlConn.setUseCaches(false);
		urlConn.setConnectTimeout(10 * 1000);
		urlConn.setReadTimeout(10 * 1000);
		urlConn.setDoOutput(true);
		urlConn.setDoInput(true);

		BufferedReader br = null;
		StringBuilder content = new StringBuilder(200);
		InputStream in = null;
		try {

			if (null == in) {
				in = urlConn.getInputStream();
			}
			if (null != in) {
				br = new BufferedReader(new InputStreamReader(in, charset));
				String line = "";
				while ((line = br.readLine()) != null) {
					content.append(line);
				}
			}

		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (null != in) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
				in = null;
			}
			if (null != br) {
				try {
					br.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
				in = null;
			}
		}
		return content.toString();
	}
}
